package com.os.repository;

import org.opensearch.action.search.SearchRequest;
import org.opensearch.client.core.CountRequest;
import org.opensearch.index.query.BoolQueryBuilder;
import org.opensearch.index.query.QueryBuilders;
import org.opensearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Component;

/**
 * 构建productSearchRequest工具类
 */
@Component
public class ProductSearchRequestBuild  {

    // 索引的name
    private static final String PRODUCTS_INDEX = "products";
    // 滚动上下文保持5分钟
    private static final String SCROLL_TIMEOUT = "5m";
    // 每批次提取的文档数量
    private static final int BATCH_SIZE = 1000;

    public static SearchRequest pageSearchRequest(Integer pageNo, Integer pageSize) {
        // 创建查询请求，指定索引名
        SearchRequest searchRequest = new SearchRequest(PRODUCTS_INDEX);

        // 构建查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询所有文档: 这个可以定义筛选条件
         sourceBuilder.query(QueryBuilders.matchAllQuery());
//        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
//                .filter(QueryBuilders.rangeQuery("id").gte(2000));
//        sourceBuilder.query(boolQuery);

        // 设置分页参数
        sourceBuilder.from((pageNo - 1) * pageSize);  // 计算从哪个位置开始
        sourceBuilder.size(pageSize);  // 设置每页的文档数量

        searchRequest.source(sourceBuilder);
        return searchRequest;
    }

    public static SearchRequest scrollSearchRequest() {
        // 初始化Scroll上下文
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询所有文档: 这个可以定义筛选条件
         sourceBuilder.query(QueryBuilders.matchAllQuery());
//        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
//                .filter(QueryBuilders.rangeQuery("id").gte(2000));
//        sourceBuilder.query(boolQuery);

        // 每批次提取的文档数量
        sourceBuilder.size(BATCH_SIZE);

        SearchRequest searchRequest = new SearchRequest(PRODUCTS_INDEX);
        searchRequest.source(sourceBuilder);
        // 滚动上下文保持5分钟
        // searchRequest.scroll(new Scroll(TimeValue.timeValueMinutes(5L)));
        searchRequest.scroll(SCROLL_TIMEOUT);
        return searchRequest;
    }

    public static CountRequest countSearchRequest() {
        // 创建一个查询请求，指定索引名
        CountRequest countRequest = new CountRequest(PRODUCTS_INDEX);
        // 构建查询条件，这里为空，表示查询所有数据
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询所有文档: 这个可以定义筛选条件
         sourceBuilder.query(QueryBuilders.matchAllQuery());
//        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
//                .filter(QueryBuilders.rangeQuery("id").gte(2000));
//        sourceBuilder.query(boolQuery);

        countRequest.source(sourceBuilder);
        return countRequest;
    }


}
